<template>
  <div id="login">
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
      label-position="right"
      status-icon
    >
      <el-form-item label="用户名" prop="username">
        <el-input v-model="ruleForm.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="userpass">
        <el-input type="password" v-model="ruleForm.userpass"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">登录</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import loginApi from "@/api/login";
export default {
  data() {
    return {
      ruleForm: {
        username: "",
        userpass: ""
      },
      rules: {
        //规则
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 7, message: "长度在 3 到 7 个字符", trigger: "blur" }
        ],
        userpass: [{ required: true, message: "请输入密码", trigger: "blur" }]
      }
    };
  },

  components: {},

  methods: {
    submitForm(ruleForm) {
      //提交
      this.$refs[ruleForm].validate(async vali => {
        if (vali) {
          try {
            //发送登录请求，获取token
            let p = await this.$store.dispatch("Login", this.ruleForm);
            if (p.flag) {
              //登录成功
              this.$message({
                message: "登录成功",
                type: "success"
              });
              this.$router.push("/");
            }
          } catch (err) {
            console.log(err);
          }
        } else {
          this.$message.error("您还没有输入完噢");
        }
      });
    },
    resetForm(ruleForm) {
      //重置
      this.$refs[ruleForm].resetFields();
    }
  }
};
</script>

<style lang='scss'>
@import "~@/assets/scss/login.scss";
#app {
  height: 100%;
}
</style>